package org.cogaen.java2d.xml;

import java.awt.Color;
import java.awt.Font;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.cogaen.core.Core;
import org.cogaen.java2d.TextVisual;
import org.cogaen.logging.LoggingService;
import org.cogaen.resource.ResourceManager;

public class TextXmlHandle extends XmlHandle {

	private static final String LOGGING_SOURCE = ResourceManager.LOGGING_SOURCE;
	private TextParser textParser;
	
	public TextXmlHandle(String resourceName, String filename) {
		super(resourceName, filename, TextParser.createFilter(resourceName));
		this.textParser = new TextParser();
	}
	
	private TextVisual createTextVisual(Core core) {
		TextVisual txtVisual;
		
		if (this.textParser.getText() != null) {
			txtVisual = new TextVisual(this.textParser.getText());
		} else {
			txtVisual = new TextVisual();
		}
		
		if (this.textParser.getFontName() != null) {
			ResourceManager resMngr = ResourceManager.getInstance(core);
			if (resMngr.hasResource(this.textParser.getFontName())) {
				txtVisual.setFont((Font) resMngr.getResource(this.textParser.getFontName()));
			} else {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "referenced resource '" + this.textParser.getFontName() + "' not found");
			}
		}
		
		if (this.textParser.getColorName() != null) {
			ResourceManager resMngr = ResourceManager.getInstance(core);
			if (resMngr.hasResource(this.textParser.getColorName())) {
				txtVisual.setColor((Color) resMngr.getResource(this.textParser.getColorName()));
			} else {
				LoggingService logger = LoggingService.getInstance(core);
				logger.logWarning(LOGGING_SOURCE, "referenced resource '" + this.textParser.getColorName() + "' not found");
			}
		}
		
		txtVisual.setOffset(this.textParser.getOffsetX(), this.textParser.getOffsetY());
		
		return txtVisual;
	}
	
	@Override
	protected Object parseXml(Core core, XMLStreamReader parser) throws XMLStreamException {
		try {
			this.textParser.parse(parser);
			return createTextVisual(core);
		} catch (ParseException e) {
			LoggingService logger = LoggingService.getInstance(core);
			logger.logWarning(LOGGING_SOURCE, "unable to load text visual '" + getName() + "': " + e.getMessage());
			return new TextVisual();
		}		
	}

}
